package com.zhy.deploy.websocket;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class SessionContext {
    private Map<String, Session> sessionMap;

    private static SessionContext context = null;

    private SessionContext() {
        sessionMap = Maps.newHashMap();
    }

    public static SessionContext getInstance(){
        if(Objects.isNull(context)){
            context = new SessionContext();
        }
        return context;
    }

    synchronized void AddSession(String sessionId,Session session) {
        if (session != null) {
            sessionMap.put(sessionId, session);
        }
    }

    synchronized void DelSession(String sessionId) throws IOException {
        if (StrUtil.isNotEmpty(sessionId)) {
            Session session = sessionMap.get(sessionId);
            if(Objects.nonNull(session)){
                if(session.isOpen()){
                    session.close();
                }
                sessionMap.remove(sessionId);
            }
        }
    }

    public synchronized Session getSession(String session_id) {
        if (session_id == null) return null;
        return sessionMap.get(session_id);
    }
}
